package dao

import (
	. "CrudProject/DataBase"
	"CrudProject/Model"
	"fmt"
	"github.com/gin-gonic/gin"
	"github.com/jinzhu/gorm"
	_ "github.com/jinzhu/gorm/dialects/mysql"
)

/*获取帖子列表*/
func GetTopicDetail(c *gin.Context) {
	//c.String(200,"获取topic id=%s的帖子",c.Param("topic_id"))
	//c.JSON(200,Model.CreateTopic(101,"帖子标题"))
	tid := c.Param("topic_id")
	topics := Model.TopicClass{}
	DataHelper.Find(&topics, tid)
	c.JSON(200, topics)
}

/*新增帖子*/
func AddTopic(c *gin.Context) {
	query := Model.TopicPlus{}
	err := c.BindJSON(&query)
	if err != nil {
		c.String(400, "参数错误%s", err.Error())
	} else {
		c.JSON(200, query)
	}
}

/*删除帖子*/
func DeleteTopic(c *gin.Context) {
	c.String(200, "删除帖子！")
}

/*必须登录*/
func MustLogin() gin.HandlerFunc {
	return func(c *gin.Context) {
		//go语言中可以用下划线表示可忽略参数
		if _, status := c.GetQuery("token"); !status {
			c.String(401, "缺少token参数")
			c.Abort()
		}
	}
}

/*获取帖子列表*/
func GetTopicList(c *gin.Context) {
	query := Model.TopicQuery{}
	err := c.BindQuery(&query)
	if err != nil {
		c.String(400, "参数错误%s", err.Error())
	} else {
		c.JSON(200, query)
	}
}

/*批量新增帖子*/
func AddTopics(c *gin.Context) {
	query := Model.Topics{}
	err := c.BindJSON(&query)
	if err != nil {
		c.String(400, "参数错误%s", err.Error())
	} else {
		c.JSON(200, query)
	}
}

/* 通过实体添加数据 */
func AddModelTopic(c *gin.Context) {
	db, _ := gorm.Open("mysql", "root:123456@tcp(127.0.0.1:3306)/leotemp?charset=utf8&loc=Local")
	//一个坑，不设置这个参数，gorm会把表名转义后加个s，导致找不到数据库的表
	db.SingularTable(true)
	db.LogMode(true)
	topics := Model.TopicClass{ClassId: 1, ClassName: "文艺", ClassRemark: "文艺类"}
	fmt.Println(db.Create(&topics).RowsAffected)

}
